package ro.upt.dcda.pricezone.s2.requests;

import javax.jms.JMSException;
import javax.jms.StreamMessage;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import ro.upt.dcda.pricezone.common.ConnectionFactory;
import ro.upt.dcda.pricezone.s2.pojo.Store;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.PrecisionModel;

public class NewStoreRequest implements S2Request {

	private String storeName;
	private String storeDescription;
	private double longitude;
	private double latitude;
	private GeometryFactory geometryFactory = new GeometryFactory(
			new PrecisionModel(PrecisionModel.FLOATING), 4269);

	public NewStoreRequest(StreamMessage msg) throws Exception {
		storeName = msg.readString();
		storeDescription = msg.readString();
		longitude = msg.readDouble();
		latitude = msg.readDouble();
	}

	public void work(StreamMessage message) throws JMSException {
		Session session = ConnectionFactory.getFactory().openSession();
		try {
			Transaction tx = session.beginTransaction();
			Point point = geometryFactory.createPoint(new Coordinate(longitude,
					latitude));
			Store store = new Store();
			store.setName(storeName);
			store.setDescription(storeDescription);
			store.setLocation(point);
			session.save(store);
			tx.commit();
			message.writeInt(1);
		} catch (HibernateException e) {
			e.printStackTrace();
			message.writeInt(0);
		} finally {
			session.close();
		}
	}
}
